<template>
	<el-select 
		class="ld-select"
		:clearable="clearable"
		:value="valueShow"
		filterable
        v-if="showTree"
        v-bind="$attrs"
		:filter-method="filterMethod"
        @visible-change="visibleChange"
		@clear="clearHandle"
		placeholder="请输入下拉树形"
        ref="treeSelectRef"
		popper-class="ld-select_tree-drop">
		<el-option :value="valueShow">
			<el-tree 
                v-if="dataType === 'static'"
				:show-checkbox="false"
				ref="selectTree"
                :expand-on-click-node="true"
				:data="allOptions"
				:props="defaultProps"
                default-expand-all
                :check-on-click-node="true"
				:node-key="defaultProps.value"
                @node-click="clickNode"
				:filter-node-method="filterNode">
                <div slot-scope="{ node, data }">
                    <div :class="defaultValue === data.value ? 'labelTextCss' : ''" :title="data.label">{{ data.label }}</div>
                </div>
			</el-tree>
            <el-tree
                v-else
                ref="selectTree"
                default-expand-all
                @node-click="clickNode"
                :node-key="lazyProps.value"
                :data="allOptions"
                :props="lazyProps"
                :load="loadNode"
                lazy>
            </el-tree>
		</el-option>
	</el-select>
</template>

<script>
import {
    sourceTestList
} from '@/api/custom/formDesigner'
export default {
    name: "tree-select",
    props: ['options', 'defaultValue', 'dataType', 'value', 'fields', 'clearable'],
    data() {
        return {
            valueShow: '',
            defaultProps: {
                value: 'value', // ID字段名
                label: 'label', // 显示名称
                children: 'children' // 子级字段名
            },
            lazyProps: {
                isLeaf: 'leaf',
                value: 'value', // ID字段名
                label: 'label', // 显示名称
                children: 'children' // 子级字段名
            },
            allOptions: [],
            idAndLabelMap: new Map(),
            showTree: true
        }
    },
    watch: {
        options: {
            handler(newVal, oldVal) {
                if (this.dataType === 'static') { //静态数据
                    this.allOptions = [...this.options]
                }
            }
        },
        dataType: {
            handler() {
                if (this.dataType === 'static') { //静态数据
                    this.allOptions = [...this.options]
                    this.loopSearchName(this.options)
                }
            },
            immediate: true
        },
        value: {
            handler (newVal) {
                if (this.dataType === 'static') {
                    this.allOptions = [...this.options]
                    this.loopSearchName(this.options)
                }
            }
        },
        fields: {
            handler (newVal) {
                this.showTree = false
                setTimeout(() => {
                    this.showTree = true
                }, 0);
            }
        }
    },
    mounted () {
        if (this.dataType === 'static') {
            this.loopSearchName(this.options)
        }
    },
    mounted () {
    },
    methods: {
        loadNode(node, resolve) {
            const _this = this
            if (node?.data?.value) {
                if (node.level === this.fields.length) {
                    resolve([])
                } else {
                    sourceTestList( this.fields[node.level].tableName).then(rsp => {
                        if (rsp.code === 0) {
                            let nodes = rsp.data?.rowMaps.map((item)=>{
                                return {
                                    label:item[_this.fields[node.level].datas[0].showName],
                                    value:item[_this.fields[node.level].datas[0].fieldName],
                                    parent: item[_this.fields[node.level].datas[0]?.parent]
                                }
                            })
                            if (node.data.value) {
                                nodes = nodes.filter(curVal => {
                                    return curVal.parent === node.data.value
                                }) || []
                            }
                            // 通过调用resolve将子节点数据返回，通知组件数据加载完成
                            setTimeout(() => {
                                resolve(nodes);
                            }, 500)
                        }
                    })
                }
            }
        },
        visibleChange () {
            if (this.dataType === 'dynamic') {
                this.allOptions = []
                this.getTableData(this.value || '')
            }
        },
        //获取表单所有数据
        async getTableData(val) {
            const _this = this
            // 新需求适配多个表单
            await sourceTestList(_this.fields[0].tableName).then(rsp => {
                if (rsp.code === 0) {
                    _this.allOptions = rsp.data?.rowMaps.map((item)=>{
                        return {
                            label: item[_this.fields[0].datas[0].showName],
                            value: item[_this.fields[0].datas[0].fieldName]
                        }
                    })
                }
            })
        },
        loopSearchName (children) {
            for (let a = 0; a < children?.length; a++) {
                const xx = children[a]
                if (xx.value + '' === this.value + '') {
                    this.valueShow = xx.label
                    return
                }
                xx.children?.length > 0 && this.loopSearchName(xx.children)
            }
        },
        clickNode(node, data){
            this.valueShow = node.label
            this.$emit('input', node.value)
            this.$emit('change', node.value)
            this.$refs['treeSelectRef'].blur()
        },
        // 清除选中
        clearHandle(){
            this.valueShow = ''
            this.$emit('change', '')
        },
        filterMethod(val){
            this.valueShow = val
            this.$refs.selectTree.filter(val)
        },
        filterNode(value, data) {
            if (!value) return true
            return data.label.indexOf(value) !== -1
        }
    }
}
</script>

<style scoped>
    .labelTextCss{
        color: #409EFF;
    }
	.el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
		height: auto;
		padding: 0;
	}
	
	.el-select-dropdown__item.selected {
		font-weight: normal;
	}
	
	ul li>>>.el-tree .el-tree-node__content {
		height: auto;
	}
	
	.el-tree-node__label {
		font-weight: normal;
	}
	
	.el-tree>>>.is-current .el-tree-node__label {
		color: #409EFF;
		font-weight: 700;
	}
	
	.el-tree>>>.is-current .el-tree-node__children .el-tree-node__label {
		color: #606266;
		font-weight: normal;
	}
	
	.ld-select_tree {
		text-align: right;
		padding-right: 20px;
		position: absolute;
		bottom: 10px;
		right: -4px;
	}
</style>

<style lang="less">
	.ld-select {
		.el-input__icon {
			line-height: 32px!important;
		}
	}
</style>
